package uk.ac.salfordcc.sccmobile;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import sccmobile.helper.*;
import sccmobile.helper.AlertDialogManager;
import sccmobile.helper.ConnectionDetector;
import sccmobile.helper.JSONParser;

public class StaffNewsActivity extends Activity implements AdapterView.OnItemClickListener {
    String username, password;
    SharedUtilities sUtils;

    /* sccmobile.helper objects */
    sccmobile.helper.ConnectionDetector cd;
    AlertDialogManager alert;
    JSONParser jsonparser;
    ProgressDialog pDialog;

    ArrayList<HashMap<String, String>> newsList;

    JSONArray albums = null;
    ListView lv;
    ListAdapter adapter;
    ArrayList<String> newsDetails;
    ArrayList<String> newsTitles;
    //String[] newsDetails;

    private static final String URL = "http://si.salfordcc.ac.uk/ws/srv_staffAnnoucements.php";
    private static final String TITLE = "title";
    private static final String STORY = "message";


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

        // Show the Up button in the action bar.
        //setupActionBar();

        /* Get username and password data */
        sUtils = new SharedUtilities(getApplicationContext());
        username = sUtils.getStoredPreference("USERNAME");      // Get the stored username
        password = sUtils.getStoredPreference("PASSWORD");      // Get the stored password
        String logStr = "scc MyStudents: Stored User = " + username + " || Stored Password = " + password;
        Log.e(logStr, "");

        /* Create Instances */
        cd = new ConnectionDetector(getApplicationContext());
        alert = new AlertDialogManager();
        jsonparser = new JSONParser();
        newsList = new ArrayList<HashMap<String, String>>();
        newsDetails = new ArrayList<String>();
        newsTitles = new ArrayList<String>();

        if(!cd.isConnectingToInternet()){
            alert.showAlertDialog(this, "Internet Connection Error", "Please connect a working internet connection.", false);
            return;
        }
        else{ Log.e("scc Connection: ", "[Enabled]"); }
        new LoadData().execute();

        setContentView(R.layout.activity_staff_news);
        lv = (ListView)findViewById(R.id.newsView);
        lv.setOnItemClickListener(this);

        /*
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3){
                Log.i("scc click: ", "YES");
            }
        });
        */
	}

    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position, long id){
        Intent intent = new Intent(getApplicationContext(), ViewNewsActivity.class);

        String[] titles = newsTitles.toArray(new String[newsTitles.size()]);
        String[] messages = newsDetails.toArray(new String[newsDetails.size()]);
        String strHTML = messages[position].replaceAll("(\\r|\\n)", "");
        String strHEAD = titles[position].replaceAll("(\\r|\\n)", "");

        intent.putExtra("HTML", strHTML);
        intent.putExtra("TITLE", strHEAD);
        startActivity(intent);
    }

    public void testStuff(int pos){
        String[] messages = newsDetails.toArray(new String[newsDetails.size()]);
        Log.i("scc Click: ", messages[pos]);


        /*
        Log.i("scc: ItemClickListener", "");
        AlertDialog.Builder builder = new AlertDialog.Builder(StaffNewsActivity.this);
        builder.setMessage("Hello")
        .setPositiveButton("Touch Me!", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                Log.e("scc Pos click: ", "Yes");
            }
        })
        .setNegativeButton("Get off!", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                Log.e("scc Neg click: ", "Yes");
            }
        });
        */
    }


	/**
	 * Set up the {@link android.app.ActionBar}.
	 */
	private void setupActionBar() {
		getActionBar().setDisplayHomeAsUpEnabled(true);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.staff_news, menu);
		return true;
	}

    public boolean onOptionsItemSelected(MenuItem item){
        switch(item.getItemId()){
            case R.id.action_exitapp:
                SharedUtilities.endApplication(this, StaffNewsActivity.this);
                return true;
            case R.id.action_settings:
                Intent intent = new Intent(StaffNewsActivity.this, SettingsActivity.class);
                startActivity(intent);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    class LoadData extends AsyncTask<String, String, String> {
        LoadData(){}

        @Override
        protected void onPreExecute(){
            super.onPreExecute();
            pDialog = new ProgressDialog(StaffNewsActivity.this);
            pDialog.setMessage("Getting news items, please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        protected String doInBackground(String... args){
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            String json = jsonparser.makeHttpRequest(URL, "GET", params, username, password);

            Log.v("THIS IS THE JSON: ", json);
            if(json != ""){
                try{
                    JSONObject jObj = new JSONObject(json);
                    if(jObj != null){
                        albums = jObj.getJSONArray("announcements");

                        if(albums != null){
                            for(int i = 0; i < albums.length(); i++){
                                JSONObject c = albums.getJSONObject(i);
                                String s_title = c.getString(TITLE);
                                String s_story = c.getString(STORY);

                                newsDetails.add(s_story);
                                newsTitles.add(s_title);

                                HashMap<String, String> map = new HashMap<String, String>();
                                map.put("title", s_title);
                                newsList.add(map);
                            }
                        }
                    }
                }
                catch(JSONException e){
                    e.printStackTrace();
                }
            }
            return null;
        }

        protected void onPostExecute(String file_url){
            pDialog.dismiss();
            runOnUiThread(new Runnable() {
                public void run() {
                    //String[] values, positions
                    adapter = new SimpleAdapter(StaffNewsActivity.this, newsList, R.layout.list_item_staffnews,
                            new String[] { TITLE, "s_title" },
                            new int[] { R.id.news_title });
                    lv.setAdapter(adapter);
                }
            });
        }
    }

}
